/*
 * @Author: jiu yin
 * @Date: 2024-05-20 18:30:54
 * @LastEditTime: 2024-07-04 15:52:14
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \studio-web-admin\src\utils\webSocket\common.js
 * jiu
 */

import { socket, addSocketNotify } from "./index"
import { update_devices_info, offline_device, deploy_application_result, deploy_map_result } from "@/api/home";
import EventBus from "@/utils/eventBus";
import { throttle } from "@/utils"
//查询设备列表
export const deviceList = () => {
   let time = null
   let time_num = 1000 * 60 * 2

   time = setInterval(() => {
      socket.send(JSON.stringify({ action: "api/query/list" }))
   }, time_num);
   //设备列表
   addSocketNotify("query/list", (msg) => {
      if (msg.action != "api/query/list") return
      console.log(msg);
      if (msg.code == 1000) {
         update_devices_info({ devices_data: msg.payload })
      }
   })
   //设备离线
   addSocketNotify("device/status", (msg) => {
      if (msg.action != "device/status") return
      console.log(msg);
      if (msg.code == 1000) {
         msg.payload.status == false && offline_device({ device_sn: msg.payload.sn })
      }
   })



   //接收某个设备的部署
   addSocketNotify("device/app/upgrade", async (msg) => {
      if (msg.action != "device/app/upgrade") return;
      updateStatus(msg.payload)
      updateStatus_map(msg.payload)
   });

   //自定义指令
   addSocketNotify("device/custom/message", async (msg) => {
      if (msg.action != "device/custom/message") return;
      upgradeStatusCmd(msg)//自定义指令询问部署状态
   });

   //自定义指令询问部署状态
   function upgradeStatusCmd(msg) {
      if (msg.code != 1000) return
      if (!msg.payload?.body) return
      let { cmd, data } = msg.payload.body
      if (cmd != "upgradeStatus") return
      updateStatus(data)
      updateStatus_map(data)
   }

}


//---------设备部署状态
async function updateStatus(data) {
   if (data?.type == "apk" && data?.sn && data?.package && data?.status && data?.version) {
      request_updateStatus(data)
   }
}

const request_updateStatus = throttle(async (data) => {
   await deploy_application_result({
      package: data.package,
      device_real_sn: data.sn,
      status: data.status,
      version: data.version,
   });
   EventBus.emit("deploy_application_result_update",)
}, 2000)


//---------地图部署状态
async function updateStatus_map(data) {
   if (data?.type == "zip" && data?.sn && data?.package && data?.status && data?.version) {
      await deploy_map_result({
         package: data.package,
         device_real_sn: data.sn,
         status: data.status,
         version: data.version,
      });
      EventBus.emit("updateStatus_map",)
   }
}

// const request_deploy_application = throttle(async (data) => {
//    await deploy_map_result({
//       package: data.package,
//       device_real_sn: data.sn,
//       status: data.status,
//       version: data.version,
//    });
//    EventBus.emit("updateStatus_map",)
// }, 2000)